package com.leyou.auth.controller;


import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author HongBo Wang
 * @data 2018/7/18 11:32
 */
@RestController
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties prop;
    /**
     * 登陆授权
     * @param username
     * @param password
     * @param request
     * @param response
     * @return
     */
    @PostMapping("accredit")
    public ResponseEntity<Void> authentication(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request,
            HttpServletResponse response){
        //登陆校验
        String token = this.authService.authentication(username,password);
        if(StringUtils.isBlank(token)){
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        //将token 写入cookie,并指定httpOnly为true,防止通过js获取和修改
        CookieUtils.setCookie(request,response,prop.getCookieName(),
                token,prop
        .getCookieMaxAge(),null,true);
        return ResponseEntity.ok().build();
    }

    /**验证用户信息
     * @param token
     * @return
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> vertifyUser(
            @CookieValue("LY_TOKEN") String token,
            HttpServletRequest request, HttpServletResponse response){
        //获取token信息
        UserInfo userInfo = null;
        try {
            //获取token信息
            userInfo = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
            //如果成功,需要刷新token
            String newToken = JwtUtils.generateToken(userInfo, prop.getPrivateKey(), prop.getExpire());
            //将token写入cookie,并指定httpOnly为true,防止通过js获取和修改
            CookieUtils.setCookie(request,response,prop.getCookieName(),newToken,prop.getCookieMaxAge(),null,true);
            //成功后直接返回
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            //异常,返回401,证明token无效
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
        }
    }
}
